import 'package:flutter/material.dart';

/// 响应式断点
class ResponsiveBreakpoints {
  /// 手机端最大宽度
  static const double mobile = 600;

  /// 平板端最大宽度
  static const double tablet = 1200;

  /// 桌面端最小宽度
  static const double desktop = 1200;

  /// 获取当前设备类型
  static DeviceType getDeviceType(double width) {
    if (width < mobile) {
      return DeviceType.mobile;
    } else if (width < desktop) {
      return DeviceType.tablet;
    } else {
      return DeviceType.desktop;
    }
  }

  /// 判断是否为手机端
  static bool isMobile(double width) => width < mobile;

  /// 判断是否为平板端
  static bool isTablet(double width) => width >= mobile && width < desktop;

  /// 判断是否为桌面端
  static bool isDesktop(double width) => width >= desktop;
}

/// 设备类型枚举
enum DeviceType {
  mobile,
  tablet,
  desktop,
}

/// 响应式值
class ResponsiveValue<T> {
  final T mobile;
  final T? tablet;
  final T? desktop;

  const ResponsiveValue({
    required this.mobile,
    this.tablet,
    this.desktop,
  });

  /// 根据屏幕宽度获取对应的值
  T getValue(double width) {
    final deviceType = ResponsiveBreakpoints.getDeviceType(width);

    switch (deviceType) {
      case DeviceType.mobile:
        return mobile;
      case DeviceType.tablet:
        return tablet ?? mobile;
      case DeviceType.desktop:
        return desktop ?? tablet ?? mobile;
    }
  }
}

/// 响应式间距
class ResponsiveSpacing extends ResponsiveValue<EdgeInsets> {
  const ResponsiveSpacing({
    required EdgeInsets mobile,
    EdgeInsets? tablet,
    EdgeInsets? desktop,
  }) : super(mobile: mobile, tablet: tablet, desktop: desktop);

  /// 预定义的响应式间距
  static const ResponsiveSpacing defaultPadding = ResponsiveSpacing(
    mobile: EdgeInsets.all(16),
    tablet: EdgeInsets.all(24),
    desktop: EdgeInsets.all(32),
  );

  static const ResponsiveSpacing smallPadding = ResponsiveSpacing(
    mobile: EdgeInsets.all(8),
    tablet: EdgeInsets.all(12),
    desktop: EdgeInsets.all(16),
  );

  static const ResponsiveSpacing largePadding = ResponsiveSpacing(
    mobile: EdgeInsets.all(24),
    tablet: EdgeInsets.all(32),
    desktop: EdgeInsets.all(40),
  );
}

/// 响应式网格
class ResponsiveGrid extends StatelessWidget {
  /// 子组件列表
  final List<Widget> children;

  /// 响应式列数
  final ResponsiveValue<int> crossAxisCount;

  /// 主轴间距
  final double mainAxisSpacing;

  /// 交叉轴间距
  final double crossAxisSpacing;

  /// 子组件宽高比
  final double childAspectRatio;

  /// 内边距
  final EdgeInsets? padding;

  /// 物理特性
  final ScrollPhysics? physics;

  /// 是否收缩包裹
  final bool shrinkWrap;

  const ResponsiveGrid({
    Key? key,
    required this.children,
    required this.crossAxisCount,
    this.mainAxisSpacing = 16,
    this.crossAxisSpacing = 16,
    this.childAspectRatio = 1,
    this.padding,
    this.physics,
    this.shrinkWrap = true,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final columnCount = crossAxisCount.getValue(constraints.maxWidth);

        return GridView.builder(
          padding: padding,
          physics: physics,
          shrinkWrap: shrinkWrap,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: columnCount,
            mainAxisSpacing: mainAxisSpacing,
            crossAxisSpacing: crossAxisSpacing,
            childAspectRatio: childAspectRatio,
          ),
          itemCount: children.length,
          itemBuilder: (context, index) => children[index],
        );
      },
    );
  }
}

/// 响应式列布局
class ResponsiveColumns extends StatelessWidget {
  /// 子组件列表
  final List<Widget> children;

  /// 响应式列数
  final ResponsiveValue<int> columns;

  /// 列间距
  final double spacing;

  /// 行间距
  final double runSpacing;

  /// 对齐方式
  final WrapAlignment alignment;

  /// 交叉轴对齐方式
  final WrapCrossAlignment crossAxisAlignment;

  const ResponsiveColumns({
    Key? key,
    required this.children,
    required this.columns,
    this.spacing = 16,
    this.runSpacing = 16,
    this.alignment = WrapAlignment.start,
    this.crossAxisAlignment = WrapCrossAlignment.start,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final columnCount = columns.getValue(constraints.maxWidth);
        final itemWidth =
            (constraints.maxWidth - (spacing * (columnCount - 1))) /
                columnCount;

        return Wrap(
          spacing: spacing,
          runSpacing: runSpacing,
          alignment: alignment,
          crossAxisAlignment: crossAxisAlignment,
          children: children.map((child) {
            return SizedBox(
              width: itemWidth,
              child: child,
            );
          }).toList(),
        );
      },
    );
  }
}

/// 响应式文本
class ResponsiveText extends StatelessWidget {
  /// 文本内容
  final String text;

  /// 响应式样式
  final ResponsiveValue<TextStyle> style;

  /// 文本对齐方式
  final TextAlign? textAlign;

  /// 最大行数
  final int? maxLines;

  /// 溢出处理
  final TextOverflow? overflow;

  const ResponsiveText(
    this.text, {
    Key? key,
    required this.style,
    this.textAlign,
    this.maxLines,
    this.overflow,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final textStyle = style.getValue(constraints.maxWidth);

        return Text(
          text,
          style: textStyle,
          textAlign: textAlign,
          maxLines: maxLines,
          overflow: overflow,
        );
      },
    );
  }
}

/// 响应式容器
class ResponsiveContainer extends StatelessWidget {
  /// 子组件
  final Widget child;

  /// 响应式宽度
  final ResponsiveValue<double?>? width;

  /// 响应式高度
  final ResponsiveValue<double?>? height;

  /// 响应式内边距
  final ResponsiveValue<EdgeInsets>? padding;

  /// 响应式外边距
  final ResponsiveValue<EdgeInsets>? margin;

  /// 装饰
  final Decoration? decoration;

  const ResponsiveContainer({
    Key? key,
    required this.child,
    this.width,
    this.height,
    this.padding,
    this.margin,
    this.decoration,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        return Container(
          width: width?.getValue(constraints.maxWidth),
          height: height?.getValue(constraints.maxWidth),
          padding: padding?.getValue(constraints.maxWidth),
          margin: margin?.getValue(constraints.maxWidth),
          decoration: decoration,
          child: child,
        );
      },
    );
  }
}

/// 响应式侧边栏布局
class ResponsiveSidebarLayout extends StatelessWidget {
  /// 侧边栏组件
  final Widget sidebar;

  /// 主内容组件
  final Widget content;

  /// 侧边栏宽度
  final double sidebarWidth;

  /// 响应式断点
  final double breakpoint;

  /// 是否显示侧边栏
  final bool showSidebar;

  /// 侧边栏位置
  final bool sidebarOnRight;

  const ResponsiveSidebarLayout({
    Key? key,
    required this.sidebar,
    required this.content,
    this.sidebarWidth = 300,
    this.breakpoint = 1024,
    this.showSidebar = true,
    this.sidebarOnRight = false,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final showSidebarInline =
            constraints.maxWidth >= breakpoint && showSidebar;

        if (showSidebarInline) {
          // 桌面端：侧边栏和内容并排显示
          final widgets = [
            SizedBox(
              width: sidebarWidth,
              child: sidebar,
            ),
            Expanded(child: content),
          ];

          return Row(
            children: sidebarOnRight ? widgets.reversed.toList() : widgets,
          );
        } else {
          // 移动端：只显示主内容
          return content;
        }
      },
    );
  }
}

/// 响应式对话框
class ResponsiveDialog extends StatelessWidget {
  /// 对话框内容
  final Widget child;

  /// 响应式宽度
  final ResponsiveValue<double>? width;

  /// 响应式高度
  final ResponsiveValue<double>? height;

  /// 响应式内边距
  final ResponsiveValue<EdgeInsets>? padding;

  /// 是否全屏显示（移动端）
  final bool fullscreenOnMobile;

  const ResponsiveDialog({
    Key? key,
    required this.child,
    this.width,
    this.height,
    this.padding,
    this.fullscreenOnMobile = true,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final isMobile = ResponsiveBreakpoints.isMobile(constraints.maxWidth);

        if (isMobile && fullscreenOnMobile) {
          return Container(
            width: double.infinity,
            height: double.infinity,
            padding: padding?.getValue(constraints.maxWidth) ??
                ResponsiveSpacing.defaultPadding.getValue(constraints.maxWidth),
            child: child,
          );
        }

        return Dialog(
          child: Container(
            width: width?.getValue(constraints.maxWidth),
            height: height?.getValue(constraints.maxWidth),
            padding: padding?.getValue(constraints.maxWidth) ??
                ResponsiveSpacing.defaultPadding.getValue(constraints.maxWidth),
            child: child,
          ),
        );
      },
    );
  }
}

/// 响应式导航栏
class ResponsiveAppBar extends StatelessWidget implements PreferredSizeWidget {
  /// 标题
  final Widget? title;

  /// 左侧组件
  final Widget? leading;

  /// 右侧操作组件列表
  final List<Widget>? actions;

  /// 底部组件
  final PreferredSizeWidget? bottom;

  /// 背景色
  final Color? backgroundColor;

  /// 前景色
  final Color? foregroundColor;

  /// 是否显示阴影
  final bool showShadow;

  /// 响应式高度
  final ResponsiveValue<double>? height;

  const ResponsiveAppBar({
    Key? key,
    this.title,
    this.leading,
    this.actions,
    this.bottom,
    this.backgroundColor,
    this.foregroundColor,
    this.showShadow = true,
    this.height,
  }) : super(key: key);

  @override
  Size get preferredSize {
    final baseHeight = height?.getValue(600) ?? kToolbarHeight; // 使用默认宽度作为参考
    final bottomHeight = bottom?.preferredSize.height ?? 0;
    return Size.fromHeight(baseHeight + bottomHeight);
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final appBarHeight =
            height?.getValue(constraints.maxWidth) ?? kToolbarHeight;
        final isMobile = ResponsiveBreakpoints.isMobile(constraints.maxWidth);

        return PreferredSize(
          preferredSize: Size.fromHeight(
              appBarHeight + (bottom?.preferredSize.height ?? 0)),
          child: AppBar(
            title: title,
            leading: leading,
            actions: actions,
            bottom: bottom,
            backgroundColor: backgroundColor,
            foregroundColor: foregroundColor,
            elevation: showShadow ? (isMobile ? 2 : 4) : 0,
            toolbarHeight: appBarHeight,
            titleSpacing: isMobile ? 16 : 24,
          ),
        );
      },
    );
  }
}

/// 响应式底部导航栏
class ResponsiveBottomNavigation extends StatelessWidget {
  /// 导航项列表
  final List<BottomNavigationBarItem> items;

  /// 当前选中索引
  final int currentIndex;

  /// 选择回调
  final void Function(int index)? onTap;

  /// 是否显示标签
  final bool showLabels;

  /// 响应式断点
  final double breakpoint;

  const ResponsiveBottomNavigation({
    Key? key,
    required this.items,
    required this.currentIndex,
    this.onTap,
    this.showLabels = true,
    this.breakpoint = 600,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final showBottomNav = constraints.maxWidth < breakpoint;

        if (!showBottomNav) {
          return const SizedBox.shrink();
        }

        return BottomNavigationBar(
          items: items,
          currentIndex: currentIndex,
          onTap: onTap,
          type: BottomNavigationBarType.fixed,
          showSelectedLabels: showLabels,
          showUnselectedLabels: showLabels,
        );
      },
    );
  }
}

/// 响应式帮助类
class ResponsiveHelper {
  /// 获取当前屏幕宽度
  static double getScreenWidth(BuildContext context) {
    return MediaQuery.of(context).size.width;
  }

  /// 获取当前屏幕高度
  static double getScreenHeight(BuildContext context) {
    return MediaQuery.of(context).size.height;
  }

  /// 获取当前设备类型
  static DeviceType getDeviceType(BuildContext context) {
    return ResponsiveBreakpoints.getDeviceType(getScreenWidth(context));
  }

  /// 判断是否为手机端
  static bool isMobile(BuildContext context) {
    return ResponsiveBreakpoints.isMobile(getScreenWidth(context));
  }

  /// 判断是否为平板端
  static bool isTablet(BuildContext context) {
    return ResponsiveBreakpoints.isTablet(getScreenWidth(context));
  }

  /// 判断是否为桌面端
  static bool isDesktop(BuildContext context) {
    return ResponsiveBreakpoints.isDesktop(getScreenWidth(context));
  }

  /// 根据设备类型返回不同的值
  static T getValue<T>(
    BuildContext context, {
    required T mobile,
    T? tablet,
    T? desktop,
  }) {
    final deviceType = getDeviceType(context);

    switch (deviceType) {
      case DeviceType.mobile:
        return mobile;
      case DeviceType.tablet:
        return tablet ?? mobile;
      case DeviceType.desktop:
        return desktop ?? tablet ?? mobile;
    }
  }
}
